package work.vcloud.baseinfo.service.impl;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import work.vcloud.baseinfo.service.intfc.BatchUpdateService;
import work.vcloud.frame.dao.OpenDao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 数据库的批量操作
 */
@Service
public class BatchUpdateServiceImpl implements BatchUpdateService {
    private Logger logger = LoggerFactory.getLogger(BatchUpdateServiceImpl.class);

    //单次操作数量
    public static final int UPDATE_COUNT = 500;

    @Autowired
    OpenDao openDao;

    /**
     * 批量插入数据
     *
     * @param sqlMapId
     * @param list
     * @throws Exception
     */
    @Override
    public void batchUpdate(String sqlMapId, List<Map<String, Object>> list, Map map) throws Exception {
        //生成id
        for (int i = 0; i < list.size(); i++) {
            Map dataMap = list.get(i);
            if (dataMap.get("UUID") == null){
                dataMap.put("UUID", UUID.randomUUID().toString());
            }
        }

        //每次插入数据的个数
        int count = UPDATE_COUNT;
        for (int i = 0; i < list.size(); i += count) {
            HashMap dataMap = new HashMap();
            dataMap.put("userInfo", map.get("userInfo"));
            dataMap.put("sqlMapId", sqlMapId);
            int endIndex = i + count < list.size() ? i + count : list.size();
            dataMap.put("dataList", list.subList(i, endIndex));
            openDao.update(dataMap);
        }
    }
}

